
const Citizen = require('../models/Citizen.js');
const IdCard = require('../models/IdCard.js');

// 维护从 Citizen 到 IdCard 的一对一关联关系
Citizen.hasOne( IdCard , {
    // 指定对方(IdCard)表中参照我方(Citizen)主键的外键
    foreignKey: 'citizen_id',
    onDelete: 'SET NULL',
    onUpdate: 'CASCADE'
});

IdCard.belongsTo( Citizen , {
    // 指示我方(IdCard)用来维护关联关系的外键
    foreignKey: 'citizen_id' 
});

Citizen.findByPk( 6 , {
    include: {
        model: IdCard,
        attributes: [ 'id' , 'cardNo' ]
    }
}).then( row => {
    return row.dataValues ;
}).then( c => {
    c.idCard = c.IdCard.dataValues;
    delete c.IdCard;
    return c ;
}).then( c => {
    console.log( c.id , c.name );
    console.log( c.idCard.id , c.idCard.cardNo );
    console.log( '- '.repeat(20) );
});

IdCard.findByPk( 4 , {
    attributes: [ 'id' , 'cardNo' ],
    include: {
        model: Citizen,
    }
}).then( row => {
    return row.dataValues ;
}).then( d => {
    d.citizen = d.Citizen.dataValues;
    delete d.Citizen;
    return d ;
}).then( d => {
    console.log( d.id , d.cardNo);
    console.log( d.citizen.id , d.citizen.name );
    console.log( '- '.repeat(20) );
});